package cn.xk.basic.controller;

import cn.xk.basic.util.AjaxResult;
import cn.xk.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传-需要[请求方式：post]
 * 下载-不需要
 * 删除-需要[请求方式：delete]
 * 修改-不需要=先删除再上传
 */
@RestController
@RequestMapping("/fastDfs")

public class FastDfsController {
    /**
     * 文件上传接口
     */
    @PostMapping
    public AjaxResult uploadFlie(@RequestPart MultipartFile file) {
        try {
            String oName = file.getOriginalFilename();
            String exeName = oName.substring(oName.lastIndexOf(".") + 1);

            String fileName = FastDfsUtils.upload(file.getBytes(), exeName);
            return AjaxResult.me().setObj(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "上传失败");
        }
    }

    /**
     * 删除接口
     */
    @DeleteMapping
    public AjaxResult deleteFile(@RequestParam("path") String path) {
        try {

            path = path.substring(1);
            String groupName = path.substring(0, path.indexOf("/"));
            String fileName = path.substring(path.indexOf("/") + 1);
            FastDfsUtils.delete(groupName, fileName);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "删除失败");
        }
    }

}
